const mysql = require('mysql')
const config = require('./config')
const {debug} = require('../utils/constant')
const {isObject} = require('../utils/index')

function connect(){
    return mysql.createConnection({
        ...config,
        multipleStatements:true
    })
}

function querySelect(sql){
    const conn = connect();
    return new Promise((resolve,reject)=>{
        debug&&console.log(sql)
        conn.query(sql,(err,res)=>{
            try{
                if(err){
                //    debug && console.log('查询失败，原因:' + JSON.stringify(err))
                   reject(err)
                }else{
                    // debug && console.log('查询成功', JSON.stringify(res))
                    resolve(res)
                }
            }
            catch(e){
                reject(e)
            }
            finally{
                conn.end()
            }

        })
    })

}

function queryOne(sql){
    const conn = connect()
    return new Promise((resolve,reject)=>{
        conn.query(sql,(err,res)=>{
            try{
                if(err){
                    reject(err)
                }else{
                    if(res&&res.length>0){
                        resolve(res[0])
                    }else{
                        resolve(null)
                    }
                }
            }catch(e){
                reject(e)
            }finally{
                conn.end()
            }

        })
    })


}

function insert(model,tableName){
    return new Promise((resolve,reject)=>{
        if(!isObject(model)){
            reject(new Error('插入数据库失败,插入数据非对象'))
        }else{
            const keys = []
            const values = []
            Object.keys(model).forEach((key)=>{
                if(model.hasOwnProperty(key)){
                    keys.push(`\`${key}\``)
                    values.push(`'${model[key]}'`)
                }
            })
            if(keys.length>0&&values.length>0){
                let sql = `INSERT INTO \`${tableName}\` (`
                const keysString = keys.join(',')
                const valuesString = values.join(',')
                sql = `${sql}${keysString}) VALUES (${valuesString})`
                debug && console.log(sql)
                const conn = connect()
                try{
                    conn.query(sql,(err,result)=>{
                        if(err){
                            reject(err)
                        }else{
                            resolve(result)
                        }
                    })
                }catch(e){
                    reject(e)
                }finally{
                    conn.end()
                }
            }else{
                reject(new Error('插入数据失败，对象中没有任何属性'))
            }
        }
    })
}

function update(model,tableName,where){
    return new Promise((resolve,reject)=>{


        let sql = `UPDATE ${tableName} SET `
        const entry = []
        Object.keys(model).forEach(c=>{
            entry.push(`\`${c}\`='${model[c]}'`)
        })
        if(entry.length>0){
            sql = `${sql}${entry.join(',')} ${where}`
            debug&&console.log(sql)
            const conn = connect()
            try{
                conn.query(sql,(err,res)=>{
                    if(err){
                        reject(err)
                    }else{
                        resolve(res)
                    }
        
                })
            }catch(e){
                reject(e)
            }finally{
                conn.end()
            }
        }


    })
}


function and(where,key,value){
    if(where==='where'){
        return `where \`${key}\`='${value}'`
    }else{
        return `${where} and \`${key}\`='${value}'`
    }
}
function andLike(where,key,value){
    if(where==='where'){
        return `where \`${key}\` like '%${value}%'`
    }else{
        return `${where} and \`${key}\` like '%${value}%'`
    }
}
module.exports = {
    querySelect,
    queryOne,
    insert,
    update,
    and,
    andLike
}